package com.likou;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * Author: 陈桂明
 * Date: 2025/9/10 15:11
 * Description: q437
 */
public class q437 {

    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode p = root;
        int ans = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                // DFS
                ans += DFS(poll, 0L, targetSum);

                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }

        return ans;
    }

    private int DFS(TreeNode root, long sum, int target) {
        if (root == null) {
            return 0;
        }

        int ans = 0;
        int val = root.val;
        sum += val;
        if (sum == target) {
            ans++;
        }
        ans += DFS(root.left, sum, target);
        ans += DFS(root.right, sum, target);

        return ans;
    }
}
